/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    ScrollView,
    Image,
    TextInput,
    ToolbarAndroid,
    TouchableHighlight,
    ProgressBarAndroid,
    Alert,
    ToastAndroid,
    Dimensions
} from 'react-native';

import md5 from 'md5'
import StringEx from '../utils/stringex'
import CommonStyles from '../styles/common';
import LoadingView from './custom/loadingView';
import { SignIn,CleanAuthrizatuon,OpenidSignIn} from '../actions/userActions';
import {Actions} from 'react-native-router-flux'
import FontAwesome from 'react-native-vector-icons/FontAwesome'
import * as QQAPI from 'react-native-qq';

var interval=null;
export default class Login extends Component {
    constructor(props) {
        super(props);
        this.state={
            userName:'',
            password:''
        };
    }
    
    componentWillMount() { 
        global.storage.load({ key:'UserLoginName',autoSync:false,syncInBackground:false}).then(ret => {
            var name=ret.UserName||'';
            if(name.length>0)
            {
                this.setState({userName:name});
            }
        }).catch( err => {
            //如果没有找到数据且没有同步方法，
            //或者有其他异常，则在catch中返回
        });      
    }
    
    onPressSignIn(){
        this.props.dispatch(CleanAuthrizatuon());
        var username=StringEx.trim(this.state.userName);
        var password = StringEx.trim(this.state.password);
        if(username.length==0||password.length==0){
            ToastAndroid.show('帐号密码不能为空',ToastAndroid.SHORT);
            return;
        }
        this.props.dispatch(SignIn(username,password));
        interval=setInterval(this.responseSignIn.bind(this),500);
    }
    
    responseSignIn(){
        if(!this.props.isLoading)
        {
            clearInterval(interval);
            //osc登录
            if(this.props.loginCatalog=='osc')
            {
                if(this.props.userInfo!=null&&this.props.userName!='')
                {
                    global.storage.save({
                        key:'UserLoginInfo',
                        rawData:{
                            UserInfo:this.props.userInfo
                        },
                        expires: 1000*3600*2
                    });
                    
                    global.storage.save({
                        key:'UserLoginName',
                        rawData:{
                            UserName:this.props.userName
                        },
                        expires: null
                    });
                    
                    if(this.props.loginResult.result)
                    {
                        Actions.pop();
                    }
                    else
                    {
                        Alert.alert('系统提示','登录失败！'+this.props.loginResult.msg);
                    }
                }
                else
                {
                    if(this.props.loginResult)
                    {
                        Alert.alert('系统提示',this.props.loginResult.msg);
                    }
                    else
                    {
                        Alert.alert('系统提示','系统异常，请稍后尝试！');
                    }
                }                
            }
            //第三方登录
            else{
                if(this.props.userInfo!=null)
                {
                    global.storage.save({
                        key:'UserLoginInfo',
                        rawData:{
                            UserInfo:this.props.userInfo
                        },
                        expires: 1000*3600*2
                    });
                }
                else
                {
                    if(this.props.loginResult)
                    {
                        if(this.props.loginResult.msg.indexOf('未找到绑定关系')>=0)
                        {
                            Actions.loginBindChoose({catalog:'qq'});
                        }
                    }
                    else
                    {
                        Alert.alert('系统提示','系统异常，请稍后尝试！');
                    }
                }
            }
            
        }         
    }
    
    onPressQQLogin()
    {
        QQAPI.login().then(response =>
        {
            this.props.dispatch(OpenidSignIn('qq',JSON.stringify(response)));
            interval=setInterval(this.responseSignIn.bind(this),500);
        });
    }
    
    render() {
        if (this.props.isLoading)
        {
            return (<LoadingView isLoading={this.props.isLoading} tip='登录中...'/>);
        }
          
        return (
            <View style={CommonStyles.container}>
                <ScrollView contentContainerStyle={[CommonStyles.padding10]}>
                    <TextInput
                        style={CommonStyles.input}
                        placeholder='邮箱/用户名' onChangeText={(text) => this.setState({userName:text})} value={this.state.userName}/>
                    <TextInput
                        style={CommonStyles.input}
                        placeholder='密码'
                        password={true} onChangeText={(text) => this.setState({password:text})} value={this.state.password}/>

                    <TouchableHighlight
                        style={[CommonStyles.button,{backgroundColor:'#5FC4D0'}]}
                        underlayColor='#87ceeb'
                        onPress={this.onPressSignIn.bind(this)}>
                        <Text style={[CommonStyles.buttonText,CommonStyles.font16]}>登  录</Text>
                    </TouchableHighlight>
                    <View style={[styles.otherLoginView]}>
                        <Text style={styles.otherLoginText}>还可以使用其他帐号登录</Text>
                        <TouchableHighlight
                            style={styles.QQLoginBg}
                            underlayColor='#fff'
                            onPress={this.onPressQQLogin.bind(this)}>
                            <FontAwesome name='qq' size={24} color='#fff'/>
                        </TouchableHighlight>
                    </View>               
                </ScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    otherLoginView:{
        flex:1,
        marginTop:30
    },
    otherLoginText:{
        fontSize:16,
        marginBottom:10
    },
    QQLoginBg:{
        width:40,
        height:40,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor:'#77C1FE',
        borderWidth: 0,
        borderRadius: 20,
    }
});
